﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CoD4_Helper
{
    public partial class CfgEditorForm : Form
    {
        /// <summary>
        /// The Config File to edit
        /// </summary>
        private ConfigFile cfg;

        //private BindingList<Utils.CfgCommand> _lst;

        public CfgEditorForm(string configPath)
        {
            InitializeComponent();
            // Instance of a CFG
            this.cfg = new ConfigFile(configPath);
        }

        private void CfgEditorForm_Load(object sender, EventArgs e)
        {
            // Load the config
            this.cfg.Load();

            // Custom Columns
            dataGridCfg.AutoGenerateColumns = false;

            DataGridViewTextBoxColumn commandColumn = new DataGridViewTextBoxColumn();
            commandColumn.DataPropertyName = "Command";
            commandColumn.HeaderText = "Command or Bind";
            DataGridViewTextBoxColumn valueColumn = new DataGridViewTextBoxColumn();
            valueColumn.DataPropertyName = "Value";
            valueColumn.HeaderText = "Value";

            dataGridCfg.Columns.Add(commandColumn);
            dataGridCfg.Columns.Add(valueColumn);
            
            // Bind the BindingList to the DataGridView
            dataGridCfg.DataSource = this.cfg.Commands;
        }

        #region Live search logic
        List<int> rowGridIndexes;

        private void txtSearchBinds_TextChanged(object sender, EventArgs e)
        {
            // Deselect the cells
            if (dataGridCfg.SelectedCells.Count != 0)
                dataGridCfg.SelectedCells[0].Selected = false;

            if (!string.IsNullOrWhiteSpace(txtSearchBinds.Text)) // if it's null don't do anything
            {
                rowGridIndexes = new List<int>();

                // Get all the founded commands
                foreach (Utils.CfgCommand item in this.cfg.Commands)
                {
                    bool containText = item.Command.ToLower().Contains(txtSearchBinds.Text.ToLower());

                    if (containText)
                        rowGridIndexes.Add(this.cfg.Commands.IndexOf(item));
                }

                // Select the first row and scroll to its position
                if (rowGridIndexes.Count != 0)
                {
                    currentGridIndex = rowGridIndexes[0];
                    dataGridCfg.Rows[rowGridIndexes[0]].Selected = true;
                    dataGridCfg.FirstDisplayedScrollingRowIndex = rowGridIndexes[0];
                    lblCurrentOcc.Text = (counter + 1).ToString();
                }
                else
                {
                    //nothing found
                    lblCurrentOcc.Text = "0";
                    currentGridIndex = 0;
                }

                // Show number of cmds found
                lblNumOccurences.Text = rowGridIndexes.Count.ToString();
            }
            else
            {
                lblNumOccurences.Text = "0";
                lblCurrentOcc.Text = "0";
                rowGridIndexes = null;
            }

            counter = 0;
        } 
        #endregion

        #region Find Next/Prev logic
        private void bntNextOcc_Click(object sender, EventArgs e)
        {
            NextIndex();
        }

        private void btnPrevOcc_Click(object sender, EventArgs e)
        {
            PrevIndex();
        }

        // used to scroll through the list
        int counter = 0;
        // store the position in the grid
        int currentGridIndex = 0;
        private void NextIndex()
        {
            if (rowGridIndexes != null && rowGridIndexes.Count != 0)
            {
                if (currentGridIndex < rowGridIndexes.Last())
                {
                    counter++;
                    dataGridCfg.Rows[rowGridIndexes[counter]].Selected = true;
                    dataGridCfg.FirstDisplayedScrollingRowIndex = rowGridIndexes[counter];
                    currentGridIndex = rowGridIndexes[counter];

                }
                else
                {
                    counter = 0;
                    currentGridIndex = rowGridIndexes[0];
                    dataGridCfg.Rows[rowGridIndexes[counter]].Selected = true;
                    dataGridCfg.FirstDisplayedScrollingRowIndex = rowGridIndexes[counter];
                }

                lblCurrentOcc.Text = (counter + 1).ToString();
            }
            else
                counter = 0;
        }

        private void PrevIndex()
        {
            if (rowGridIndexes != null && rowGridIndexes.Count != 0)
            {
                if (currentGridIndex > rowGridIndexes.First())
                {
                    counter--;
                    dataGridCfg.Rows[rowGridIndexes[counter]].Selected = true;
                    dataGridCfg.FirstDisplayedScrollingRowIndex = rowGridIndexes[counter];
                    currentGridIndex = rowGridIndexes[counter];
                }
                else
                {
                    counter = rowGridIndexes.Count - 1;
                    currentGridIndex = rowGridIndexes.Last();
                    dataGridCfg.Rows[rowGridIndexes[counter]].Selected = true;
                    dataGridCfg.FirstDisplayedScrollingRowIndex = rowGridIndexes[counter];
                }

                lblCurrentOcc.Text = (counter + 1).ToString();
            }
            else
            {
                counter = 0;
            }

        } 
        #endregion

        private void btnExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            sfd.Title = "Save your new CFG!";
            sfd.Filter = "Config files (*.cfg)|*.cfg";

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                cfg.Save(sfd.FileName);
            }

        }
        
        
        private void btnAddCmd_Click(object sender, EventArgs e)
        {
            AddNewCfgCmd("seta");
        }

        private void btnAddBind_Click(object sender, EventArgs e)
        {
            AddNewCfgCmd("bind");
        }

        /// <summary>
        /// Add a new CfgCommand in the list binded to the DataGridView and begin the editing 
        /// </summary>
        /// <param name="cmdType"></param>
        private void AddNewCfgCmd(string cmdType)
        {
            switch (cmdType)
            {
                case "bind": this.cfg.Commands.Add(new Utils.CfgCommand("def", "def", "bind"));
                    break;
                case "seta": this.cfg.Commands.Add(new Utils.CfgCommand("def", "def", "seta"));
                    break;

                default: this.cfg.Commands.Add(new Utils.CfgCommand("def", null, null));
                    break;
            }
            
            // scroll to the bottom
            dataGridCfg.FirstDisplayedScrollingRowIndex = dataGridCfg.Rows.Count - 1;
            // Select last row (the one i have just added)
            dataGridCfg.Rows[dataGridCfg.Rows.Count - 1].Selected = true;
            // Select the first cell
            dataGridCfg.SelectedCells[0].Selected = true;
            // start EditMode for the selected cell
            dataGridCfg.BeginEdit(true);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            dataGridCfg.DataSource = null;
            this.cfg.Load();

            dataGridCfg.DataSource = this.cfg.Commands;
        }

       

        


        
    }
}
